package com.study.controller;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.github.pagehelper.PageInfo;
import com.study.model.mdao.AnniversaryMapper;
import com.study.model.mdao.CareDAO;
import com.study.model.mdao.CompetitorsMapper;
import com.study.model.mdao.DemantMapper;
import com.study.model.mdao.OffersDAO;
import com.study.model.mdao.OpportunityMapper;
import com.study.model.mdao.SolutionMapper;
import com.study.model.pojo.Customer;
import com.study.services.AddresdetailService;
import com.study.services.AnniversaryService;
import com.study.services.CareService;
import com.study.services.CollectionService;
import com.study.services.CusmshfitServices;
import com.study.services.CustomerService;
import com.study.services.CustomerconsolidationServices;
import com.study.services.DemantService;
import com.study.services.HighSeasService;
import com.study.services.LinkmanService;
import com.study.services.OpportunityService;
import com.study.services.OrderfromServices;
import com.study.services.UserService;

@Controller
public class CustomerController {
	@Autowired
	CollectionService service;
	@Autowired
	CustomerService cs;
	@Autowired
	UserService us;
	@Autowired
	OrderfromServices oredeservices;
	@Autowired
	CustomerconsolidationServices solid;
	@Autowired
	CusmshfitServices cusm;
	@Autowired
	LinkmanService ls;
	@Autowired
	AddresdetailService as;
	@Autowired
	HighSeasService highSeasService;

	/**
	 * 文件上传Wcx
	 */
	@PostMapping("/custormerfile")
	public ModelAndView upload(MultipartFile file, HttpServletRequest request, HttpSession session) {
		// file存储了上传的文件的所有信息
		ModelAndView mv = new ModelAndView("customer/nwecumter");
		try {
			System.out.println(file);
			// 转存到指定目录
			// 1、获取当前工程发布所在的物理路径，文件上传目录WebContent/upload
			ServletContext context = request.getServletContext();
			System.out.println("context:" + context);
			// 2、全球唯一码作为新的文件名
			String newname = UUID.randomUUID().toString().toUpperCase();
			// 3、获取源文件的后缀名（png）
			String suffix = "." + FilenameUtils.getExtension(file.getOriginalFilename());
			// 4、创建新文件（存储在硬盘上，使用物理路径。）
			// File new_file=new
			// File("G:\\git\\CRM\\src\\main\\resources\\static\\gimg"+"/"+newname+suffix);
			// File new_file = new
			// File("D:\\Gitwork\\CRM\\src\\main\\resources\\static\\images\\imagess" + "/"
			// + newname + suffix);
			File new_file = new File(
					"D:\\Users\\Administrator\\git\\CRM1\\src\\main\\resources\\static\\images\\imagess" + "/" + newname
							+ suffix);
			String img = "../images/imagess/" + newname + suffix;
			System.out.println("拼接的图片路径======：" + img);
			session.setAttribute("img", img);
			// 5、将源文件转存到新文件上
			file.transferTo(new_file);
			mv.addObject("1", "13456");
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return mv;
	}

	/**
	 * 采集页转化成客户
	 * 
	 * @param dname
	 * @return
	 */
	@GetMapping("/addCustomerByColle")
	public ModelAndView addCustomerByColle(HttpServletRequest request, HttpSession session) {
		String id = request.getParameter("id");
		String useIdColle = request.getParameter("useIdColle");
		String useid = session.getAttribute("useid").toString();

		// 修改采集表信息的状态
		service.editorState(id);
		System.out.println("我已经改变了状态" + useIdColle + "sss");
		// 判断该条信息是否为表单转化来的
		service.editorForm(id, 1);
		if ("".equals(useIdColle)) {
			session.setAttribute("useIdColle", useIdColle);
		}

		JSONObject colle = service.selectBycid(id);
		ModelAndView mv = new ModelAndView("/customer/nwecumter");
		mv.addObject("colle", colle);
		mv.addObject("up", new JSONObject());
		mv.addObject("highs", highSeasService.selecthigh(useid));

		return mv;
	}

	// 测试JPA方式的数据是否通畅
	/**
	 * 访问地址：http://localhost:8080/emp/add 点击提交之后，post提交，添加员工信息 Wcx
	 * 
	 * @param model
	 * @return
	 */
	@GetMapping("customer")
	public ModelAndView deptAdd() {
		// @GetMapping没有带斜杠/，默认的视图是jsp/add.jsp页面
		ModelAndView mv = new ModelAndView("customer/customer");
		System.out.println("来了老弟");
		return mv;
	}

	/**
	 * Wcx
	 * 
	 * @param dname
	 */
	@GetMapping("addcus")
	public ModelAndView addDept() {
		System.out.println("新建进来了");
		ModelAndView mv = new ModelAndView("customer/nwecumter");
		JSONObject jsonObject = new JSONObject();
		mv.addObject("up", jsonObject);
		mv.addObject("colle", new JSONObject());
		mv.addObject("highs",  new JSONObject() );
		return mv;
	}

	/**
	 * wjl
	 * 
	 * @return
	 */
	@RequestMapping(value = "/bilianggongxing")
	public ModelAndView getCusmshiAll() {
		List<JSONObject> getfindCustmoer = cusm.getfindCustmoer();
		ModelAndView mv = new ModelAndView("customer/piliangchognzhi");
		mv.addObject("piliang", getfindCustmoer);
		return mv;
	}

	/**
	 * 实现带数据跳转到客户合并页面 wjl
	 * 
	 * @return
	 */
	@RequestMapping(value = "/customers")
	public ModelAndView getCustmerlist() {
		ModelAndView mv = new ModelAndView("customer/kehuhebing");
		return mv;
	}

	@PostMapping("/selectcusethebing")
	@ResponseBody
	public JSONArray getCustkehubing(HttpServletRequest request) {
		// 获取用户id
		String useid = request.getSession().getAttribute("useid").toString();
		System.out.println(request.getSession().getAttribute("useid"));
		List<JSONObject> findByCusShowAndUser = null;
		// 判断用户角色
		List<String> findUsername = us.getFindUsername(Integer.parseInt(useid));
		JSONArray array = new JSONArray();
		// 判断是否是老板
		for (String rolese : findUsername) {
			if (rolese.equals("1")) {
				findByCusShowAndUser = cs.getFindCusmtionUser(null);
				break;
			} else {
				findByCusShowAndUser = cs.getFindCusmtionUser(useid + "");
			}
		}
		for (JSONObject customer : findByCusShowAndUser) {
			JSONObject obj = new JSONObject();
			obj.put("value", customer.getString("cus_name"));
			array.add(obj);
		}
		System.out.println(array);
		return array;
	}

	/**
	 * @param cust         合并 的客户
	 * @param cusit2被合并的客户
	 * @return
	 */
	@PostMapping("anniForm")
	@ResponseBody
	public JSONObject getsehes(@RequestParam("aname") String cust, @RequestParam("aname1") String cusit2) {
		JSONObject obj = new JSONObject();
		Customer custsm = new Customer();
		custsm.setCusName(cust);

		// 判断客户是否存在
		if (cs.getfindCustName(cust) != null && cs.getfindCustName(cusit2) != null) {
			System.out.println(cust + "\t" + cusit2);
			if (oredeservices.getfindByCust(cust)) {

				// 添加合并记录
				boolean addCusm = solid.addCusm(1, cust, cusit2);
				if (addCusm) {
					// 实现用户状态修改
					boolean updateCust = cs.updateCust(cust);
					System.out.println("合并成功");
					obj.put("typese", "合并成功!");

				} else {
					obj.put("typese", "合并失败");

					System.out.println("合并失败");
				}
			} else {
				obj.put("typese", "存在未完成的订单");

				System.out.println("存在未完成的订单");
			}
		} else {
			obj.put("typese", "不存在该客户");

			System.out.println("不存在该客户");
		}
		System.out.println(obj + "     obj");
		return obj;
	}

	/**
	 * 实现显示跳转到客户合并记录页面
	 * 
	 * @return
	 */
	@GetMapping("/selectkehubing")
	@ResponseBody
	public ModelAndView getCustomerconsolidation() {
		ModelAndView mv = new ModelAndView("customer/kehuhebingjilu");
		// List<JSONObject> findAll = solid.getFindAll(1,2);
		return mv;
	}

	@PostMapping("customer/kehuhebing")
	@ResponseBody
	public List<JSONObject> findsekehubingjilu(int currentPage, int pagesize) {
		List<JSONObject> findAll = solid.getFindAll(currentPage, pagesize);
		for (JSONObject jsonObject : findAll) {
			System.out.println(jsonObject + "                     合并记录");
		}
		return findAll;
	}

	/**
	 * 添加数据传输
	 * 
	 * @param namese
	 * @return
	 */
	@PostMapping("addcustomer")
	@ResponseBody
	public ModelAndView aa(String namese, String src, String custer, String famoney, String state, String region,
			String privoder, String regionxiao, String dignxing, String dignji, String textarea4, String cumeradiss,Integer high,
			HttpSession session, HttpServletRequest request, HttpServletResponse response) {
		ModelAndView mv = new ModelAndView("/error");
		if (src != "") {
			src = src.substring(21);
		}
		String imgs = "../gimg/nullimg.png";
		if (session.getAttribute("img") != null) {
			imgs = request.getSession().getAttribute("img").toString();
		}
		String useIdColle = (String) request.getSession().getAttribute("useIdColle");
		String useid = null;
		if (useIdColle == null) {
			useid = request.getSession().getAttribute("useid").toString();
		}

		System.out.println(high + "  " + custer + "  " + famoney + "  " + state + "  " + region + "  " + privoder
				+ "  " + regionxiao + "  " + dignxing + "  " + dignji + "  " + textarea4);
		System.err.println("-----------------------------------------------------------------------------");
		boolean flag = cs.addcustomer(namese, imgs, custer, famoney, state, region, privoder, regionxiao, dignxing,
				dignji, textarea4, useid,high);
		
		 request.getSession().removeAttribute("useIdColle");

		if (flag) {
			JSONObject jsonObject1 = cs.selectBywhere(namese, custer, textarea4);
			String cusid = jsonObject1.getString("cus_id") + "";
			List<JSONObject> attribute = (List<JSONObject>) session.getServletContext().getAttribute("mansitem");
			attribute.add(jsonObject1);
			String adid = as.selectmax();
			int result = as.address(adid, cumeradiss, custer, famoney);
			if (result == 1) {
				int type = 1231;
				int result1 = ls.addlinmanforcus(custer, famoney, type, cusid, adid);
			}
			mv = new ModelAndView("/customer/customer");
		} else {
			mv = new ModelAndView("/error");
		}
		return mv;
	}

	/**
	 * 带条件的分页查询 Wcx
	 * 
	 * @param input
	 * @param selects
	 * @param currentPage
	 * @param pagesize
	 * @param session
	 * @param request
	 * @return
	 */

	@PostMapping("customer/TJcustomers")
	@ResponseBody
	public String getForm3(String input, String selects, int currentPage, int pagesize, HttpSession session,
			HttpServletRequest request) {
		String useid = request.getSession().getAttribute("useid").toString();
		List<JSONObject> list = cs.selectBySel(input, selects, useid);
		PageInfo<JSONObject> pager = new PageInfo<JSONObject>(list);

		/*
		 * for (JSONObject jsonObject : list) { System.out.println("地址：" +
		 * jsonObject.get("ad_address")); System.out.println("图片路劲"+
		 * jsonObject.get("cus_img")); }
		 */

		String json = JSONObject.toJSONString(pager);
		return json;
	}

	/**
	 * Wcx 修改客户的数据回显
	 * 
	 * @param linid
	 * @return
	 */
	@GetMapping("updatecus")
	public ModelAndView updatecus(Integer id) {
		int cusid = id.intValue();
		ModelAndView mv = new ModelAndView("customer/nwecumter");
		JSONObject jsonObject = cs.selectBycusid(cusid);
		System.out.println(jsonObject);
		mv.addObject("up", jsonObject);
		mv.addObject("colle", new JSONObject());
		mv.addObject("highs", new JSONObject());
		return mv;
	}

	/**
	 * 修改客户信息
	 * 
	 * @param cusid
	 * @param namese
	 * @param custer
	 * @param famoney
	 * @param state
	 * @param region
	 * @param privoder
	 * @param regionxiao
	 * @param dignxing
	 * @param dignji
	 * @param textarea4
	 * @return
	 */
	@PostMapping("updatecustomer")
	@ResponseBody
	public ModelAndView updatecustomer(String cusid, String namese, String custer, String famoney, String state,
			String region, String privoder, String regionxiao, String dignxing, String dignji, String textarea4,
			HttpServletRequest request, HttpSession session) {
		String useid = request.getSession().getAttribute("useid").toString();
		ModelAndView mv = new ModelAndView("/error");
		System.out.println(custer + "         aa");
		String img = "../gimg/nullimg.png";
		if (session.getAttribute("img") != null) {
			img = request.getSession().getAttribute("img").toString();
		}
		if (state == null) {
			state = "1121";
		}
		boolean update = cs.update(cusid, namese, custer, famoney, state, region, privoder, regionxiao, dignxing,
				dignji, textarea4, useid, img);
		System.out.println("客户：  " + cusid + "   " + namese + "   " + custer);
		System.out.println("电话：   " + famoney + "  " + state + "   " + region + "   " + privoder + "   " + regionxiao
				+ "   " + dignxing + "   " + dignji + "   " + textarea4 + "   " + useid + "   " + img);
		if (update) {
			mv = new ModelAndView("/customer/customer");
		}
		return mv;
	}

	/**
	 * 带参跳转到分享页面 wjl
	 * 
	 * @return
	 */
	@GetMapping("/chuste")
	public ModelAndView getKehugogniuang() {
		ModelAndView mv = new ModelAndView("/customer/addkehugongxiang");
		List<JSONObject> findUserAll = us.getFindUserAll();
		for (JSONObject jsonObject : findUserAll) {
			System.out.println(jsonObject + "                      xmdsdsds");
		}
		mv.addObject("userall", findUserAll);
		System.out.println("我来了iframe啊啊啊啊啊");
		return mv;

	}

	/**
	 * wjl
	 * 
	 * @return
	 */
	@GetMapping("kehuzhuangyi")
	public ModelAndView getKehuzhuangyi() {
		ModelAndView mv = new ModelAndView("/customer/addkehuzhuangyi");

		List<JSONObject> findUserAll = us.getFindUserAll();
		for (JSONObject jsonObject : findUserAll) {
			System.out.println(jsonObject + "                      xmdsdsds");
		}
		mv.addObject("userall", findUserAll);

		return mv;
	}

	/**
	 * 分页查询 wjl
	 */
	@PostMapping("customer/kehufneixng")
	@ResponseBody
	public List<JSONObject> getForm1(int currentPage, int pagesize, String input, HttpServletRequest request) {
		System.out.println("你到底进来了没有啊");
		String useid = request.getSession().getAttribute("useid").toString();
		/*
		 * System.out.println(useid+"                   useid");
		 * System.out.println(input+"          customer/kehufneixng ");
		 */
		List<JSONObject> list = cusm.selectByPagerse(currentPage, pagesize, input, Integer.parseInt(useid));
		return list;
	}

	/**
	 * wjl 根据客户id删除客户分享记录
	 * 
	 * @param vals
	 * @return
	 */
	@PostMapping("customer/kehufneixngdelect")
	@ResponseBody
	public JSONObject delectKefufenxiang(@RequestParam("vals") String vals) {
		JSONObject obj = new JSONObject();
		int delectCushfitById = cusm.delectCushfitById(Integer.parseInt(vals + ""));
		System.out.println(delectCushfitById);
		if (delectCushfitById == 1) {
			obj.put("delct", "删除成功");
		} else {
			obj.put("delct", "删除失败");
		}
		return obj;
	}

	/**
	 * 客户视图
	 * 
	 * @return
	 */
	@RequestMapping("/cusview")
	public ModelAndView person(HttpServletRequest request, HttpSession session) {
		ModelAndView mv = new ModelAndView("profile");
		String id = request.getParameter("id");
		if (id==null ) {
			id = session.getAttribute("cusview").toString();
		}
		JSONObject cu = cs.queryCus(id);
		mv.addObject("cu", cu);
       System.out.println(id);
		// 客户id
		session.setAttribute("cusview", Integer.parseInt(id));
		// 查询客户记录
		mv.addObject("jilu", cs.findJilu(id));
        JSONObject js =cs.selectthree(id);
		mv.addObject("threeView", js);
		
		return mv;
	}

	/**
	 * 根据条件查询视图queryTime
	 */
	@PostMapping("/queryTime")
	@ResponseBody
	public List<JSONObject> queryTime(Integer type, String custid) {
		System.out.println(type + "-----" + custid);
		List<JSONObject> time = cs.selectBytime(custid, type);
		System.out.println(time);
		return time;
	}

	/**
	 * 时间轴
	 */
	@RequestMapping("/time")
	public ModelAndView time(HttpSession session) {
		String id =  session.getAttribute("cusview").toString();
		ModelAndView mv = new ModelAndView("/timeline_v2");
		
		// 时间轴
		List<JSONObject> time = cs.selectBytime(id, null);
		System.out.println(time);
		mv.addObject("time", time);

		// 时间记录
		mv.addObject("timeCount", cs.findTimeByCount(id));
		return mv;

	}
/**
 * 修改三定一节点
 */
	
	@PostMapping("/customer/updatethree")
	@ResponseBody
	public ModelAndView updatethree(String qualitative, String grading,String ration,
			HttpServletRequest request, HttpSession session) {
		String id =  session.getAttribute("cusview").toString();
		String useid = request.getSession().getAttribute("useid").toString();
		
		boolean flag =  cs.updatethree(id,qualitative,grading,ration,useid);
		
		System.out.println(qualitative+"我在这呢"+grading +"   " +ration +"dddd" +id);
		ModelAndView mv = new ModelAndView("profile");
		return mv;
	}

	
	
	/**
	 * 客户视图中三定一节
	 * 
	 * @return
	 */
	@RequestMapping("/three")
	public ModelAndView updatethree(HttpServletRequest request, HttpSession session) {
		String id = request.getParameter("id");
		JSONObject js =cs.selectthree(id);
		
		ModelAndView mv = new ModelAndView("/customer/three");
		mv.addObject("threeView", js);
		return mv;
	}

	/**
	 * 根据不同的类型查询时间轴
	 */

}
